package springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import springboot.Controller.dto.CollectorDTO;
import springboot.Controller.dto.UserDTO;
import springboot.common.Constants;
import springboot.entity.LjhsCollector;
import springboot.entity.LjhsUser;
import springboot.exception.ServiceException;
import springboot.mapper.LjhsCollectorMapper;
import springboot.service.ILjhsCollectorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import springboot.utils.TokenUtil;
import springboot.utils.TokenUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hys
 * @since 2022-06-02
 */
@Service
public class LjhsCollectorServiceImpl extends ServiceImpl<LjhsCollectorMapper, LjhsCollector> implements ILjhsCollectorService {

    private static final Log LOG=Log.get();
    @Override
    public CollectorDTO login(CollectorDTO collectorDTO) {
        LjhsCollector onex=getColl(collectorDTO);
        if (onex!=null){
            BeanUtil.copyProperties(onex,collectorDTO,true);
            String token = TokenUtil.genToken(onex.getCollectorId().toString(), onex.getPassword());
            collectorDTO.setToken(token);
            return collectorDTO;
        }else{
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
    }

    @Override
    public LjhsCollector register(CollectorDTO collectorDTO) {
        LjhsCollector one=getCollectorInfo(collectorDTO);
        if (one==null){
            one=new LjhsCollector();
            BeanUtil.copyProperties(collectorDTO,one,true);
            save(one);
        }else{
            throw new ServiceException(Constants.CODE_600,"用户已存在");
        }
        return one;

    }
    private LjhsCollector getCollectorInfo(CollectorDTO collectorDTO){
        QueryWrapper<LjhsCollector> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("collector",collectorDTO.getCollector());
        queryWrapper.eq("password",collectorDTO.getPassword());
        queryWrapper.eq("realname",collectorDTO.getRealname());
        queryWrapper.eq("phone",collectorDTO.getPhone());
        LjhsCollector one;
        try{
            one = getOne(queryWrapper);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }
    private LjhsCollector getColl(CollectorDTO collectorDTO){
        QueryWrapper<LjhsCollector> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("collector",collectorDTO.getCollector());
        queryWrapper.eq("password",collectorDTO.getPassword());
        LjhsCollector onex;
        try{
            onex = getOne(queryWrapper);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return onex;
    }

}
